using System;
using System.IO;
using System.Collections;
using MSHelpLib;

namespace MSHelpLib.BaseCode
{
	/// <summary>
	/// Summary description for FileArchive.
	/// </summary>
	public class FileArchive
	{		
		private ArrayList	m_Entries=new ArrayList();
		private string		m_FileName="";
	

		/// <summary>
		/// The FileArchive ctor will create a new FileArchive object. If the file specified already 
		/// exists, it will read the directory of files. Otherwise it will create an empty file archive
		/// </summary>
		/// <param name="FileName"></param>
		public FileArchive(string FileName)
		{		
			m_Entries.Clear();
			m_FileName=FileName;
			if (File.Exists(m_FileName))
				LoadCompoundFile();
		}

		/// <summary>
		/// Adds a new file to the File Archive, and copies the data from the specified stream object into
		/// the FileArchive, and the Archive directory is re-written at the end of the file.
		/// </summary>
		/// <param name="FileName"></param>
		/// <param name="st"></param>
		public void AddFile(string FileName, Stream st)
		{
			// We must have a valid stream
			if (st==null)
				throw new ArgumentNullException("The st parameter can not be null. It must be a Stream Based object");

			if (FindFile(FileName)!=null)
				throw new ArgumentNullException("The Filename '"+FileName+"' is already present in the directory");
			

			// Determine location to add new file
			long WritePos=0;
			FileStream fs=new FileStream(m_FileName,FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None);
			if (fs.Length>0)
			{				
				fs.Seek(-8,SeekOrigin.End);
				BinaryReader br=new BinaryReader(fs);

				WritePos=(long)br.ReadUInt32();
				
				fs.Seek(WritePos,SeekOrigin.Begin);
			}

			// Create new directory entry
			FileArchiveEntry Entry=new FileArchiveEntry();
			Entry.FileName=FileName;		
			Entry.Offset=(UInt32)WritePos;
			Entry.Length=(UInt32)st.Length;
			m_Entries.Add(Entry);

			// Copy new stream to Compound file
			int bufferSize=0x4000;
			byte []buffer=new byte[bufferSize];
			st.Seek(0,SeekOrigin.Begin);
			int BytesRead=0;
			do
			{
				BytesRead=st.Read(buffer,0,bufferSize);
				fs.Write(buffer,0,BytesRead);
			}
			while (BytesRead==bufferSize);
			st.Close();
			
			// Write new directory
			UInt32 DirLoc=(UInt32)fs.Position;
			UInt32 DirCount=(UInt32)m_Entries.Count;
			BinaryWriter bw=new BinaryWriter(fs);
			foreach(FileArchiveEntry DirEntry in m_Entries)
			{
				DirEntry .WriteEntry(bw);
			}
			bw.Write((UInt32)DirLoc);
			bw.Write((UInt32)DirCount);
			fs.Close();						
		}		

		/// <summary>
		/// LoadCompoundFile will read the FileArchive directory into memory
		/// </summary>		
		public void LoadCompoundFile()
		{			
			m_Entries.Clear();
			FileStream fs=new FileStream(m_FileName,FileMode.Open,FileAccess.Read,FileShare.Read);
			BinaryReader br=new BinaryReader(fs);
			br.BaseStream.Seek(-8,SeekOrigin.End);

			UInt32 DirLoc=br.ReadUInt32();
			UInt32 DirCount=br.ReadUInt32();

			br.BaseStream.Seek(DirLoc,SeekOrigin.Begin);
			for(int i=0;i<DirCount;i++)			
			{
				FileArchiveEntry Entry=new FileArchiveEntry();
				Entry.ReadEntry(br);
				m_Entries.Add(Entry);
			}
						
			fs.Close();				
		}

		/// <summary>
		/// Extract a file from the compound file into a PartFileStream object
		/// </summary>
		/// <param name="FileName"></param>
		/// <returns></returns>
		public PartFileStream ExtractFile(string FileName)
		{
			FileArchiveEntry FoundEntry=FindFile(FileName);
			if (FoundEntry==null)
				return null;
			return ExtractFile(FoundEntry);
		}

        /// <summary>
        /// Extracts the file.
        /// </summary>
        /// <param name="Entry">The entry.</param>
        /// <returns></returns>
		public PartFileStream ExtractFile(FileArchiveEntry Entry)
		{
			FileStream fs=new FileStream(m_FileName,FileMode.Open,FileAccess.Read,FileShare.Read);
			PartFileStream pfs=new PartFileStream(fs,Entry.Offset,Entry.Length);
			return pfs;
		}

		/// <summary>
		/// Finds an FileArchiveEntry by the given name
		/// </summary>
		/// <param name="FileName"></param>
		/// <returns></returns>
		public FileArchiveEntry FindFile(string FileName)
		{			
			foreach(FileArchiveEntry Entry in m_Entries)
			{
				if (Entry.FileName.ToLower()==FileName.ToLower())
					return Entry;
			}
			return null;
		}

        /// <summary>
        /// Deletes the file.
        /// </summary>
        /// <param name="FileName">Name of the file.</param>
		public void DeleteFile(string FileName)
		{
			FileArchiveEntry FoundEntry=FindFile(FileName);
			if (FoundEntry==null)
				return;
        
			string TempFile=Path.ChangeExtension(m_FileName,".tmp");
			if (File.Exists(TempFile))
				File.Delete(TempFile);
			File.Copy(m_FileName,TempFile);
			File.Delete(m_FileName);
			
			m_Entries.Clear();
			FileArchive TempArchive=new FileArchive(TempFile);
			foreach(FileArchiveEntry Entry in TempArchive.m_Entries)
			{
				if (Entry.FileName==FoundEntry.FileName)
					continue;
				
				PartFileStream pfs=TempArchive.ExtractFile(Entry);
				AddFile(Entry.FileName,pfs);
			}
		}
	}

    /// <summary>
    /// 
    /// </summary>
	public class FileArchiveEntry
	{
        /// <summary>
        /// 
        /// </summary>
		public string	FileName="";
        /// <summary>
        /// 
        /// </summary>
		public UInt32	Offset=0;
        /// <summary>
        /// 
        /// </summary>
		public UInt32	Length=0;

        /// <summary>
        /// Writes the entry.
        /// </summary>
        /// <param name="st">The st.</param>
		public void WriteEntry(BinaryWriter st)
		{
			st.Write(FileName);
			st.Write((UInt32)Offset);
			st.Write((UInt32)Length);
		}

        /// <summary>
        /// Reads the entry.
        /// </summary>
        /// <param name="st">The st.</param>
		public void ReadEntry(BinaryReader st)
		{
			FileName=st.ReadString();
			Offset=st.ReadUInt32();
			Length=st.ReadUInt32();
		}
	}

	/// <summary>
	/// The PartFileStream class creates a stream based object which will only allow the caller to access
	/// a limited part of another file. Access is read only.
	/// </summary>
	public class PartFileStream : Stream
	{		
		private FileStream	m_FileStream=null;
		private UInt32		m_Start=0;
		private UInt32		m_Length=0;

        /// <summary>
        /// Initializes a new instance of the <see cref="PartFileStream"/> class.
        /// </summary>
        /// <param name="fs">The fs.</param>
        /// <param name="Start">The start.</param>
        /// <param name="Length">The length.</param>
		public PartFileStream(FileStream fs, UInt32 Start, UInt32 Length)
		{
			m_FileStream=fs;
			if (!fs.CanRead)
				throw new ArgumentNullException("fs","The stream specified does not have read access");
			if (fs.CanWrite)
				throw new ArgumentNullException("fs","The stream specified not have write access, and PartFileStream is only read access");
			if (!fs.CanSeek)
				throw new ArgumentNullException("fs","The stream specified does not have seek access");
					
			m_FileStream.Seek(Start,SeekOrigin.Begin);
			m_Start=Start;
			m_Length=Length;			
		}

        /// <summary>
        /// Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
        /// </summary>
		public override void Close()
		{
			m_FileStream.Close();			
		}

        /// <summary>
        /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
        /// </summary>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
		public override void Flush()
		{
		}

        /// <summary>
        /// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
        /// </summary>
        /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param>
        /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
        /// <returns>
        /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
        /// </returns>
        /// <exception cref="T:System.ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length. </exception>
        /// <exception cref="T:System.ArgumentNullException">
        /// 	<paramref name="buffer"/> is null. </exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        /// 	<paramref name="offset"/> or <paramref name="count"/> is negative. </exception>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        /// <exception cref="T:System.NotSupportedException">The stream does not support reading. </exception>
        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
		public override int Read(byte[] buffer, int offset, int count)
		{
			int Count=count;
			if (Position+count>m_Length)
			{
				Count=(int)(m_Length-Position);
			}
			return m_FileStream.Read(buffer,offset,Count);
		}

        /// <summary>
        /// When overridden in a derived class, sets the position within the current stream.
        /// </summary>
        /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param>
        /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"/> indicating the reference point used to obtain the new position.</param>
        /// <returns>
        /// The new position within the current stream.
        /// </returns>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        /// <exception cref="T:System.NotSupportedException">The stream does not support seeking, such as if the stream is constructed from a pipe or console output. </exception>
        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
		public override long Seek(long offset, SeekOrigin origin)
		{
			long rc=m_FileStream.Seek(m_Start+offset,origin);
			return m_FileStream.Position-m_Start;
		}

        /// <summary>
        /// Sets the length.
        /// </summary>
        /// <param name="length">The length.</param>
		public override void SetLength(long length)
		{			
		}

        /// <summary>
        /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
        /// </summary>
        /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream.</param>
        /// <param name="count">The number of bytes to be written to the current stream.</param>
        /// <exception cref="T:System.ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is greater than the buffer length. </exception>
        /// <exception cref="T:System.ArgumentNullException">
        /// 	<paramref name="buffer"/> is null. </exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        /// 	<paramref name="offset"/> or <paramref name="count"/> is negative. </exception>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        /// <exception cref="T:System.NotSupportedException">The stream does not support writing. </exception>
        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
		public override void Write(byte[] buffer, int offset, int count)
		{
		}

		// Properties
        /// <summary>
        /// When overridden in a derived class, gets a value indicating whether the current stream supports reading.
        /// </summary>
        /// <value></value>
        /// <returns>true if the stream supports reading; otherwise, false.</returns>
		public override bool CanRead	{ get {return true;} }
        /// <summary>
        /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
        /// </summary>
        /// <value></value>
        /// <returns>true if the stream supports seeking; otherwise, false.</returns>
		public override bool CanSeek	{ get {return true;} }
        /// <summary>
        /// When overridden in a derived class, gets a value indicating whether the current stream supports writing.
        /// </summary>
        /// <value></value>
        /// <returns>true if the stream supports writing; otherwise, false.</returns>
		public override bool CanWrite	{ get {return false;} }
        /// <summary>
        /// When overridden in a derived class, gets the length in bytes of the stream.
        /// </summary>
        /// <value></value>
        /// <returns>A long value representing the length of the stream in bytes.</returns>
        /// <exception cref="T:System.NotSupportedException">A class derived from Stream does not support seeking. </exception>
        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
		public override long Length		{ get {return m_Length;} }
        /// <summary>
        /// When overridden in a derived class, gets or sets the position within the current stream.
        /// </summary>
        /// <value></value>
        /// <returns>The current position within the stream.</returns>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        /// <exception cref="T:System.NotSupportedException">The stream does not support seeking. </exception>
        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
		public override long Position	
		{ 
			get 
			{
				return m_FileStream.Position-m_Start;
			} 
			set
			{
				Seek(value,SeekOrigin.Begin);
			}
		}
	}
}


/*
 * <File 1 Data>
 * <File 2 Data>
 * .
 * .
 * .
 * <File n Data> 
 * <Directory>
 *		<FileName, Offset to Start of data (UInt32), Length of data(UInt32)>
 *		<FileName, Offset to Start of data (UInt32), Length of data(UInt32)>
 *		.
 *		.
 *		<FileName, Offset to Start of data (UInt32), Length of data(UInt32)>
 * <Offset to Start of Directory (UInt32)>
 * <Number of Directory Entries (UInt32)>
 * 
 */
